package cs5300;

import java.util.Calendar;
import java.util.Hashtable;
import java.util.Iterator;

public class CacheTable {
	static Hashtable<String, sessionState> cacheTable = new Hashtable<String, sessionState>();
	static CacheTable ct;
	static int maxSession = 1000;

	private CacheTable() {
	}

	// Create & return a new cache table
	public static CacheTable getInstance() {
		if (ct == null) {
			ct = new CacheTable();
		}
		return ct;
	}

	// insert a session into the table
	public boolean insertSession(sessionState ss) {
		if (full()) {
			clean();
			if (full()) {
				return false;
			}
		}
		cacheTable.put(ss.cookie.sessionID, ss);
		return true;
	}

	// Check if table is full
	public boolean full() {
		return cacheTable.size() >= maxSession;
	}

	// Return the State according to given sessionID
	public sessionState getState(String sessionID) {
		sessionState ss = cacheTable.get(sessionID);
		return ss;
	}

	// Update the value of the sessionID
	public boolean updateState(sessionState ss) {
		if (!cacheTable.containsKey(ss.cookie.sessionID)) {
			return false;
		}
		cacheTable.put(ss.cookie.sessionID, ss);
		return true;
	}

	// Remove a sessionID
	public boolean removeState(String key) {
		if (!cacheTable.containsKey(key)) {
			return false;
		}
		cacheTable.remove(key);
		return true;
	}

	// Clean the expired session
	public void clean() {
		Iterator<sessionState> iter = cacheTable.values().iterator();
		while (iter.hasNext()) {
			if (iter.next().discard_time > Calendar.getInstance().getTimeInMillis()) {
				iter.remove();
			}
		}
	}
}
